package com.stephen.redisdemo.atomic;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @author: stephen
 * @create: 2020-03-01 11:13
 * @description: 多线程之间顺序循环调用,用多个condition实现
 *
 * 题目: 多线程之间顺序调用,实现A -> B -> C 三个线程启动
 * A打印5次,B打印10次,C打印15次
 * 再继续
 * A打印5次,B打印10次,C打印15次
 * ...
 * 总共来3轮
 */
class MyShareData {
    // 设计: number为1时,A工作,2->B,3->C
    private int number = 1;
    private Lock lock = new ReentrantLock();
    // 创建三个condition,ABC各一个
    private Condition c1 = lock.newCondition();
    private Condition c2 = lock.newCondition();
    private Condition c3 = lock.newCondition();

    public void print5() {
        lock.lock();
        try {
            while (number != 1) {
                // A等待
                c1.await();
            }
            // A工作
            for (int i = 0; i < 5; i++) {
                System.out.println(Thread.currentThread().getName() + "\t" + i);
            }
            // 改变条件
            number = 2;
            // 唤醒B
            c2.signal();
        } catch (Exception e) {

        } finally {
            lock.unlock();
        }
    }
    public void print10() {
        lock.lock();
        try {
            while (number != 2) {
                // B等待
                c2.await();
            }
            // B工作
            for (int i = 0; i < 10; i++) {
                System.out.println(Thread.currentThread().getName() + "\t" + i);
            }
            // 改变条件
            number = 3;
            // 唤醒C
            c3.signal();
        } catch (Exception e) {

        } finally {
            lock.unlock();
        }
    }

    public void print15() {
        lock.lock();
        try {
            while (number != 3) {
                // C等待
                c3.await();
            }
            // C工作
            for (int i = 0; i < 15; i++) {
                System.out.println(Thread.currentThread().getName() + "\t" + i);
            }
            // 改变条件
            number = 1;
            // 唤醒A
            c1.signal();
        } catch (Exception e) {

        } finally {
            lock.unlock();
        }
    }

}

public class SequenceReentrantLockDemo {

    public static void main(String[] args) {
        MyShareData myShareData = new MyShareData();
        new Thread(() -> {
            for (int i = 0; i < 3; i++) {
                myShareData.print5();
            }
        },"A").start();
        new Thread(() -> {
            for (int i = 0; i < 3; i++) {
                myShareData.print10();
            }
        },"B").start();
        new Thread(() -> {
            for (int i = 0; i < 3; i++) {
                myShareData.print15();
            }
        },"C").start();

    }

}
